const {exec, escape} = require('../db/mysql')
// 根据身份证号获取学员预约信息
const getReverseByUsername = async (username) => {
  username = escape(username)
  const sql = `select *
               from reverse
               where identify = ${username}`
  return await exec(sql).then(rows => {
    return rows[0] || {}
  })
}
// 新增一条预约记录
const newReverse = async ({identify, name, select_date, select_interval_time, submit_time, coach_id}) => {
  identify = escape(identify)
  name = escape(name)
  select_date = escape(select_date)
  select_interval_time = escape(select_interval_time)
  submit_time = escape(submit_time)
  coach_id = escape(coach_id)
  const sql = `insert into reverse(identify, name, select_date, select_interval_time, submit_time, issure, coach_id)
               values (${identify}, ${name}, ${select_date}, ${select_interval_time}, ${submit_time}, 0, ${coach_id})`
  return await exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}
// 删除预约
const delReverse = async (id) => {
  id = escape(id)
  const sql = `delete
               from reverse
               where id = ${id}`
  return await exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}
// 更新预约
const updateReverse = async ({id, select_date, select_interval_time, submit_time, confirm_time, issure}) => {
  id = escape(id)
  select_date = escape(select_date)
  select_interval_time = escape(select_interval_time)
  submit_time = escape(submit_time)
  confirm_time = escape(confirm_time)
  issure = escape(issure)
  let sql = `update reverse set `
  if (select_date !== 'NULL') {
    sql += `select_date          = ${select_date},
            select_interval_time = ${select_interval_time},
            submit_time          = ${submit_time}`
  }
  if (confirm_time !== 'NULL') {
    sql += `confirm_time         = ${confirm_time},
            issure               = ${issure}`
  }
  sql += ` where id = ${id}`
  console.log(sql)
  return await exec(sql).then(data => {
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}
// 根据教练编号获取学员预约信息
const getReverseListByCoachId = async (coach_id) => {
  coach_id = escape(coach_id)
  const sql = `select * from reverse where coach_id = ${coach_id}`
  return await exec(sql)
}

module.exports = {
  getReverseByUsername,
  newReverse,
  delReverse,
  updateReverse,
  getReverseListByCoachId
}
